<template>
	<skeleton :skeleton="{name:'examsub'}"
			  :showSkeleton="showSkeleton">
		<block slot="content">
			<view class="container">
				<view class="not-btn">
					<view class="head">
						<view class="head-left">
							<text class="head-text">{{subject.subjectTypeDesc}}</text>
							<image class="head-img" src="/static/exam/spot.png"></image>
							<text class="head-textype">{{getChoiceType}}</text>
						</view>
						<view class="head-right">
							<text class="head-num" v-if="examType!=0">{{dataIndex+1}}/{{subjectSize}}</text>
							<view class="sure-btn" v-if="examType==0" @click="sure">确定</view>
						</view>
					</view>
					<v-question-exam
						:dataIndex="dataIndex"
						:subject="subject"
						:subjectSize="subjectSize"
						@checkChange="checkChange"
						@radioChange="radioChange">
					</v-question-exam>
					<v-analysis
					v-if="examType==0"
					:subject="subject"
					:class='[subject.showAnalysis==1?"show":"hide"]'>
				</v-analysis>
				</view>
				<view class="btn">
					<view class="btn-left" @click="lastSub()">
						<text class="btn-textl">上一题</text>
					</view>
					<view class="btn-right" @click="nextSub()">
						<text class="btn-text">{{isLastSub}}</text>
					</view>
				</view>
			</view>
		</block>
	</skeleton>
</template>

<script>
  import examService from '@/services/exam/exam';
  import navbarExam from '@/mixins/common/navbar/exam';
  import {mapState, mapGetters, mapMutations} from 'vuex';
	import vQuestionExam from './fragments/vquestionexam';
	import vAnalysis from './fragments/vanalysis';
    const service = new examService(false);
    const saveAnswer = new Set();
    export default {
        mixins:[navbarExam],
        computed: {
            ...mapGetters({
                getIndex:'exam/getIndex'
            }),
            dataIndex(){
                return this.getIndex;
            },
            subject(){
               return Object.keys(this.subjectDetail).length != 0 ? this.subjectDetail[this.dataIndex]: ""

            },
			getChoiceType() { //页面展示单选还是多选 1 单选 2 多选
				if (this.subject != "") {
				    return this.subject.choiceType == 1 ? "单选题":"多选题"
				}
			},
            getSubjectChoices() { //获取答案选项
				return this.subject != "" ? this.subject.subjectChoices:""
            },
            isLastSub(){//判断是否为最后一题，如果是，下一题的按钮需要变成提交
                if(this.subjectSize !=  0){
                    return this.subjectSize != this.dataIndex+1 ? "下一题" : "提交"
                }
            }
        },
        data() {
            return {
                swiperData:[],
                showSkeleton:true,
                currentIndex:0,
                examId:'',
                paperId:'',//试卷id，非必传
                examType:'',//做题类型：0:自主练习  1:快速练习 2:智能自测 3:模拟大赛 4:历年真题  ...
                subjectDetail:[],
                paperTypeDesc:'',
                subjectSize:0,//试卷题目总数
                payload:{
                    index:0
				},
                startTime:'',
                endTime:'',
                h:0,
                m:0,
                ms:0,
                s:0,
                time:0,
                str:"00:00:00",
                examBarData : [
                    {
                        img:'/static/exam/examBar02.png',
                        text:'收藏',
                        id:'collect',
                        type:'static',
                        onPress:(context)=>{
                            uni.showToast({
                                title: '收藏',
                                duration: 2000,
                                icon:'none'
                            });
                        }
                    },
                    {
                        img:'/static/exam/examBar03.png',
                        text:'答题卡',
                        id:'card',
                        type:'static',
                        onPress:(context)=>{
                            //TODO:先将考题数据保存,这里可以不组合数据，只需调用接口的时候全部保存即可
                            let exam = {
                                paperId:context.paperId,
                                paperTypeDesc:context.paperTypeDesc,
                                subjectDetail:context.subjectDetail,
                                subjectSize:context.subjectSize,
                                startTime:context.startTime,
                                endTime:context.endTime
                            }
                            context.updateExam(exam)
							uni.navigateTo({
								url:"/pages/exam/answerSheet"
							})
                        }
                    },
                    {
                        img:'/static/exam/examBar04.png',
                        text:'00:00:00',
                        type:'dynamics',
                        id:'time',
                        onPress:(context)=>{
                            uni.showToast({
                                title: '时间',
                                duration: 2000,
                                icon:'none'
                            });
                        }
                    }
                ]


            }
        },
        components:{
			vQuestionExam,
			vAnalysis
        },
        onLoad(query) {
            this.uploadIndex();//初始化试卷
			this.examType = query.examType;
			this.paperId = query.paperId;
			//继续答题 参数类型
			this.examId = query.examId
            if(this.examId != "" && this.examId != undefined){//继续答题 逻辑
                let param = {
                    examId:this.examId,
                }
                this.goonAnswer(param)
            }else{
                //不同类型的练习，调用接口不同
                if(this.examType==0){//自主练习
                    let param = {
                        paperId:this.paperId,
                    }
                    this.selfExam(param);
                }else if(this.examType==2){//智能自测
                    let param = {
                        pointType:query.pointType,
                        amount:query.amount
                    }
                    this.smartTest(param);
                }else{//其它
                    let param = {
                        paperId:this.paperId,
                    }
                    this.getSubject(param);
                }
            }
        },
		onShow(){

		},
        onUnload(){
            this.stop();
        },
        methods: {
            ...mapMutations({
                uploadIndex:'exam/uploadIndex',
                updateIndex:'exam/updateIndex',
                updateExam:'exam/updateExam',
                increaseIndex:'exam/increaseIndex',
                decreaseIndex:'exam/decreaseIndex'
            }),
            timeRender:(context,text='00:00:01')=>{
                // #ifdef APP-PLUS
                const $this = context;
                //$this.examDynamicsBar.reset();
                const {top} = context.specs;
                const richtext= `<img src="/static/exam/examBar04.png" width="27px" height="20px"/>`+
                    `<br/><font style="font-size:8px;">${text}</font>`;
                $this.examDynamicsBar.drawRichText(richtext,
                    {
                        top:'9px',
                        left:'0px',
                        width:'100%',
                        height:'100%'
                    },
                    {
                        onClick:function(e){
                            $this.examBarData[3].onPress($this);
                        }
                    },
                    'time'
                );
                // #endif
            },
            async getSubject(param){
                //const startAdverte = await service.paperDetail(_this.paperId)
                service.paperDetail(param).then(response=>{
                    this.setData(response);
				}).then(()=>{
                    this.showSkeleton = false;//页面请求完成，取消骨架屏展示
                });
               // console.log('subjectDetail:',this.subjectDetail)
            },
			//继续答题
			goonAnswer(param){
                service.getExaming(param).then(response=>{
                    this.setData(response);
                    this.payload.index = 2//继续答题 定位学生当前答题编号，暂时写死
                    this.updateIndex(this.payload);
                }).then(()=>{
                    this.showSkeleton = false;//页面请求完成，取消骨架屏展示
                });
			},
			//智能自测
			smartTest(param){
				service.smartTest(param).then(response=>{
					this.setData(response);
				}).then(()=>{
                    this.showSkeleton = false;//页面请求完成，取消骨架屏展示
                });
			},
			//自主练习
			selfExam(param){
				service.selfExam(param).then(response=>{
					this.setData(response);
				}).then(()=>{
                    this.showSkeleton = false;//页面请求完成，取消骨架屏展示
                });
			},
			setData(startAdverte){
				let _this = this
				 if(startAdverte.success){
				   _this.subjectDetail = startAdverte.result.subjectDetail
				   _this.subjectSize = startAdverte.result.subjectSize
				   _this.paperTypeDesc = startAdverte.result.paperTypeDesc
				   _this.start()//第一题记录用户做题时间
				   _this.startTime = new Date().getTime();
				}else{
				    _this.showModel(startAdverte.message)
				
				}
			},
            lastSub(){
                let _this = this
                saveAnswer.clear();
                if(_this.dataIndex != 0){
                    //展示前面一题
                    _this.reset()
                    _this.decreaseIndex()// _this.dataIndex--
                    _this.time = _this.subjectDetail[_this.dataIndex].useDuration
                    _this.start()
                }else{
                    _this.tip("已经是第一题了")
                }
            },
            nextSub(){
                let _this = this
                saveAnswer.clear();
                if(_this.subjectDetail[_this.dataIndex ].selectChoice == ''){
                    uni.showModal({
                        content: "您还没有选择答案,确定进入下一题吗？",
                        success: function (res) {
                            if (res.confirm) {
                                _this.nextSubGo()
                            } else if (res.cancel) {
                                // console.log('用户点击取消');
                            }
                        }
                    });
                }else{
                    _this.nextSubGo()
                }


            },
            nextSubGo(){
                let _this = this
                if(_this.dataIndex != (Number(_this.subjectSize)-1)){
                    //展示后面一题
                    _this.increaseIndex();//_this.dataIndex++
                    _this.subjectDetail[_this.dataIndex].useDuration = _this.time
                    _this.stop()
                    _this.reset()
                    _this.start()
                }else{
                    uni.redirectTo({//关闭当前页面，跳转到应用内的某个页面。
                        url: '/pages/exam/result?paperId='+this.paperId
                    })
                }

            },

            radioChange(chose){
                let _this = this;
                for(let i = 0; i < _this.getSubjectChoices.length; i++){
                    if(_this.getSubjectChoices[i].choiceId == chose){
                        _this.getSubjectChoices[i].isChose = 1;//0未选中，1选中
                        _this.subject.selectChoice = chose //保存用户答案
                    }else{
                        _this.getSubjectChoices[i].isChose = 0;//0未选中，1选中
                    }
                }


            },
            checkChange(chose){//多选
                let _this = this
                //判断选中项
                for(let i = 0; i < _this.getSubjectChoices.length; i++){
                    if(_this.getSubjectChoices[i].choiceId == chose){
                        if( _this.getSubjectChoices[i].isChose == 0){//0未选中，1选中
                            _this.getSubjectChoices[i].isChose = 1;

                        }else{
                            _this.getSubjectChoices[i].isChose = 0;//0未选中，1选中   取消选中
                          }
                    }
                }
                //保存选中项
                saveAnswer.add(chose);
                console.log("1111", saveAnswer)
                _this.subject.selectChoice =  Array.from(saveAnswer)
                console.log("2222", saveAnswer)
                console.log("3333", _this.subject.selectChoice)

            },
            timer(){   //定义计时函数
                this.ms=this.ms+1000;         //毫秒
                if(this.ms>=1000){
                    this.ms=0;
                    this.s=this.s+1;         //秒
                }
                if(this.s>=60){
                    this.s=0;
                    this.m=this.m+1;        //分钟
                }
                if(this.m>=60){
                    this.m=0;
                    this.h=this.h+1;        //小时
                }
                this.str =this.toDub(this.h)+":"+this.toDub(this.m)+":"+this.toDub(this.s);
                // #ifdef APP-PLUS
                if(this.examDynamicsBar.isVisible()){
                   // console.log('str:',this.str)
                    this.timeRender(this,this.str);
                }
                // #endif
            },
            start(){  //开始
                this.time=setInterval(this.timer,1000);
            },

            stop(){  //暂停
                clearInterval(this.time);
            },
            reset(){  //重置
                clearInterval(this.time);
                this.h=0;
                this.m=0;
                this.ms=0;
                this.s=0;
                this.str="00:00:00";
            },

            toDub(n){  //补0操作
                if(n<10){
                    return "0"+n;
                }
                else {
                    return ""+n;
                }
            },
            tip(mes){
                uni.showToast({
                    title: mes,
                    duration: 2000,
                    icon:'none'
                });
            },
            showModel(mes){
                if (mes!=undefined){
                    uni.showModal({
                        title: '提示',
                        content: mes,
                        success: function (res) {
                            if (res.confirm) {
                                //console.log('用户点击确定');
                            } else if (res.cancel) {
                                // console.log('用户点击取消');
                            }
                        }
                    });
                }
            },
			//确定，显示解析
			sure(){
				if(this.subject!=false){
					this.subjectDetail[this.dataIndex].useDuration = this.time;
					this.stop();//停止计时
					//TODO:判断是否答对
					
					this.subject.showAnalysis = 1;
				}
			}


        },
        onBackPress(){
            uni.showModal({
                content: "确定要退出练习？退出后未完成的练习可在‘历史答题’记录中继续完成",
                success: function (res) {
                    if (res.confirm) {
                        uni.switchTab({
                            url: '/pages/tabbar/home/index'
                        });
                    } else if (res.cancel) {
                        // console.log('用户点击取消');
                    }
                }
            });
            return true;
        }
    }

</script>

<style  lang='scss' scoped>
    .container{
       height:100%;background:#fff;
    }
   .head {
   	position: relative;
   	height: 100upx;
   	line-height: 100upx;
   	margin: 0 20upx;
   
   	&-left {
   		position: absolute;
   		display: inline-block;
   		width: 75%;
   		left: 0;
   	}
   
   	&-right {
   		position: absolute;
   		display: inline-block;
   		right: 0;
   		vertical-align: middle;
   		width: 20%;
   		text-align: right;
   	}
   
   	&-text {
   		font-size: 30upx;
   		color: #5ea1f8;
   		font-weight: bold;
   	}
   
   	&-img {
   		width: 24upx;
   		height: 28upx;
   	}
   
   	&-textype {
   		font-size: 24upx;
   		color: #666;
   	}
   
   	&-i {
   		display: inline-block;
   		margin-right: 50upx;
   	}
   
   	&-ico {
   		margin-top: 20upx;
   		display: inline-block;
   		width: 40upx;
   		height: 40upx;
   		text-align: center;
   		background: #999;
   		border-radius: 50%;
   		color: #fff;
   	}
   
   	&-num {
   		display: inline-block;
   		color: #5ea1f8;
   		font-size: 24upx;
   	}
   }
   
   .line {
   	width: 100%;
   	height: 1upx;
   	border-bottom: 1upx solid #eee;
   }
   .sure-btn {
   	display: inline-block;
   	width: 100upx;
   	height: 60upx;
   	line-height: 60upx;
   	text-align: center;
   	background-color: #5ea1f8;
   	border-radius: 8upx;
   	font-size: 28upx;
   	color: #ffffff;
   }
   .not-btn{
	   margin-bottom: 90upx;
   }

    .btn{
        position:fixed;bottom:0;left:0;width:100%;text-align: center;line-height:80upx;
        &-left{
            display:inline-block;width:50%;height:80upx;background:#fff;box-shadow:0 -1upx 10upx #ccc;
        }
        &-right{
            display:inline-block;width:50%;height:80upx;background:#5ea1f8;box-shadow: 0 -1upx 10upx #ccc;
        }
        &-textl{
            font-size:28upx;color:#333;
        }
        &-text{
            font-size:28upx;color:#fff;
        }
    }
.show{
	display: block;
}
.hide{
	display: none;
}



</style>

<style  lang='scss'>
    page{
        height:100%;
    }
</style>